import React, { useState, useEffect } from 'react';
import { Routes, Route, Link, NavLink, useNavigate } from 'react-router-dom';
import { userService, articleService, categoryService, tagService } from '../../services/api';
import { BsPersonFill, BsFileEarmarkTextFill, BsTagFill, BsFolderFill, BsTrash, BsPencil } from 'react-icons/bs';

// 用户管理组件
const UserManagement = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const response = await userService.getAllUsers();
        setUsers(response.data);
        setLoading(false);
      } catch (err) {
        setError('获取用户列表失败');
        setLoading(false);
      }
    };
    
    fetchUsers();
  }, []);
  
  const handleDeleteUser = async (userId) => {
    if (!window.confirm('确定要删除此用户吗？此操作不可撤销！')) return;
    
    try {
      await userService.deleteUser(userId);
      // 刷新用户列表
      const response = await userService.getAllUsers();
      setUsers(response.data);
    } catch (err) {
      setError('删除用户失败');
    }
  };
  
  if (loading) {
    return (
      <div className="flex justify-center py-8">
        <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary-600"></div>
      </div>
    );
  }
  
  if (error) {
    return (
      <div className="bg-red-100 text-red-800 p-4 rounded-md mb-4">
        {error}
      </div>
    );
  }
  
  return (
    <div>
      <h2 className="text-xl font-bold mb-6 text-dark-800 dark:text-dark-200">用户管理</h2>
      
      <div className="bg-white dark:bg-dark-800 rounded-lg shadow overflow-hidden">
        <table className="min-w-full divide-y divide-gray-200 dark:divide-dark-700">
          <thead className="bg-gray-50 dark:bg-dark-700">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">用户</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">邮箱</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">角色</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">文章数</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">状态</th>
              <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody className="bg-white dark:bg-dark-800 divide-y divide-gray-200 dark:divide-dark-700">
            {users.map(user => (
              <tr key={user.id}>
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="flex items-center">
                    {user.avatar ? (
                      <img className="h-10 w-10 rounded-full mr-3" src={user.avatar} alt={user.username} />
                    ) : (
                      <div className="h-10 w-10 rounded-full bg-gray-200 dark:bg-dark-600 flex items-center justify-center mr-3">
                        <BsPersonFill className="text-gray-500 dark:text-gray-400" />
                      </div>
                    )}
                    <div>
                      <div className="text-sm font-medium text-dark-800 dark:text-dark-200">{user.username}</div>
                      <div className="text-sm text-gray-500 dark:text-gray-400">ID: {user.id}</div>
                    </div>
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                  {user.email}
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <div className="flex space-x-1">
                    {user.roles.map(role => (
                      <span 
                        key={role} 
                        className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${
                          role === 'ROLE_ADMIN' 
                            ? 'bg-red-100 text-red-800 dark:bg-red-800 dark:text-red-100' 
                            : 'bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-100'
                        }`}
                      >
                        {role.replace('ROLE_', '')}
                      </span>
                    ))}
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                  {user.articleCount}
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  <span className={`px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${
                    user.enabled 
                      ? 'bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-100' 
                      : 'bg-red-100 text-red-800 dark:bg-red-800 dark:text-red-100'
                  }`}>
                    {user.enabled ? '启用' : '禁用'}
                  </span>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  <button
                    onClick={() => handleDeleteUser(user.id)}
                    className="text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300 ml-3"
                  >
                    <BsTrash />
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// 内容管理组件
const ContentManagement = () => {
  const [articles, setArticles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const navigate = useNavigate();
  
  useEffect(() => {
    const fetchArticles = async () => {
      try {
        const response = await articleService.getArticles(0, 100);
        setArticles(response.data.content);
        setLoading(false);
      } catch (err) {
        setError('获取文章列表失败');
        setLoading(false);
      }
    };
    
    fetchArticles();
  }, []);
  
  const handleDeleteArticle = async (articleId) => {
    if (!window.confirm('确定要删除此文章吗？此操作不可撤销！')) return;
    
    try {
      await articleService.deleteArticle(articleId);
      // 刷新文章列表
      const response = await articleService.getArticles(0, 100);
      setArticles(response.data.content);
    } catch (err) {
      setError('删除文章失败');
    }
  };
  
  if (loading) {
    return (
      <div className="flex justify-center py-8">
        <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary-600"></div>
      </div>
    );
  }
  
  if (error) {
    return (
      <div className="bg-red-100 text-red-800 p-4 rounded-md mb-4">
        {error}
      </div>
    );
  }
  
  return (
    <div>
      <h2 className="text-xl font-bold mb-6 text-dark-800 dark:text-dark-200">内容管理</h2>
      
      <div className="bg-white dark:bg-dark-800 rounded-lg shadow overflow-hidden">
        <table className="min-w-full divide-y divide-gray-200 dark:divide-dark-700">
          <thead className="bg-gray-50 dark:bg-dark-700">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">文章</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">作者</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">分类</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">浏览量</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">发布时间</th>
              <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody className="bg-white dark:bg-dark-800 divide-y divide-gray-200 dark:divide-dark-700">
            {articles.map(article => (
              <tr key={article.id}>
                <td className="px-6 py-4">
                  <div className="text-sm font-medium text-dark-800 dark:text-dark-200">{article.title}</div>
                  <div className="text-sm text-gray-500 dark:text-gray-400 truncate max-w-xs">
                    {article.content.replace(/<[^>]*>/g, '').substring(0, 50)}...
                  </div>
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                  {article.author?.username || '未知'}
                </td>
                <td className="px-6 py-4 whitespace-nowrap">
                  {article.category ? (
                    <span className="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800 dark:bg-blue-800 dark:text-blue-100">
                      {article.category.name}
                    </span>
                  ) : (
                    <span className="text-sm text-gray-500 dark:text-gray-400">无分类</span>
                  )}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                  {article.views}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                  {new Date(article.createdAt).toLocaleDateString('zh-CN')}
                </td>
                <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  <button
                    onClick={() => navigate(`/articles/edit/${article.id}`)}
                    className="text-indigo-600 dark:text-indigo-400 hover:text-indigo-900 dark:hover:text-indigo-300"
                  >
                    <BsPencil />
                  </button>
                  <button
                    onClick={() => handleDeleteArticle(article.id)}
                    className="text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300 ml-3"
                  >
                    <BsTrash />
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// 分类和标签管理组件
const CategoryTagManagement = () => {
  const [categories, setCategories] = useState([]);
  const [tags, setTags] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [newCategory, setNewCategory] = useState({ name: '', description: '' });
  const [newTag, setNewTag] = useState({ name: '' });
  
  useEffect(() => {
    const fetchData = async () => {
      try {
        const [categoriesRes, tagsRes] = await Promise.all([
          categoryService.getCategories(),
          tagService.getTags()
        ]);
        
        setCategories(categoriesRes.data);
        setTags(tagsRes.data);
        setLoading(false);
      } catch (err) {
        setError('获取分类和标签失败');
        setLoading(false);
      }
    };
    
    fetchData();
  }, []);
  
  const handleAddCategory = async (e) => {
    e.preventDefault();
    if (!newCategory.name.trim()) return;
    
    try {
      await categoryService.createCategory(newCategory);
      // 刷新分类列表
      const response = await categoryService.getCategories();
      setCategories(response.data);
      setNewCategory({ name: '', description: '' });
    } catch (err) {
      setError('添加分类失败');
    }
  };
  
  const handleAddTag = async (e) => {
    e.preventDefault();
    if (!newTag.name.trim()) return;
    
    try {
      await tagService.createTag(newTag);
      // 刷新标签列表
      const response = await tagService.getTags();
      setTags(response.data);
      setNewTag({ name: '' });
    } catch (err) {
      setError('添加标签失败');
    }
  };
  
  const handleDeleteCategory = async (id) => {
    if (!window.confirm('确定要删除此分类吗？此操作不可撤销！')) return;
    
    try {
      await categoryService.deleteCategory(id);
      // 刷新分类列表
      const response = await categoryService.getCategories();
      setCategories(response.data);
    } catch (err) {
      setError('删除分类失败');
    }
  };
  
  const handleDeleteTag = async (id) => {
    if (!window.confirm('确定要删除此标签吗？此操作不可撤销！')) return;
    
    try {
      await tagService.deleteTag(id);
      // 刷新标签列表
      const response = await tagService.getTags();
      setTags(response.data);
    } catch (err) {
      setError('删除标签失败');
    }
  };
  
  if (loading) {
    return (
      <div className="flex justify-center py-8">
        <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary-600"></div>
      </div>
    );
  }
  
  if (error) {
    return (
      <div className="bg-red-100 text-red-800 p-4 rounded-md mb-4">
        {error}
      </div>
    );
  }
  
  return (
    <div>
      <h2 className="text-xl font-bold mb-6 text-dark-800 dark:text-dark-200">分类与标签管理</h2>
      
      <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
        {/* 分类管理 */}
        <div>
          <h3 className="text-lg font-semibold mb-4 text-dark-700 dark:text-dark-300">分类管理</h3>
          
          <form onSubmit={handleAddCategory} className="mb-6 bg-white dark:bg-dark-800 p-4 rounded-lg shadow">
            <div className="mb-4">
              <label className="label" htmlFor="categoryName">分类名称</label>
              <input
                type="text"
                id="categoryName"
                className="input"
                value={newCategory.name}
                onChange={(e) => setNewCategory({ ...newCategory, name: e.target.value })}
                required
              />
            </div>
            <div className="mb-4">
              <label className="label" htmlFor="categoryDescription">分类描述</label>
              <input
                type="text"
                id="categoryDescription"
                className="input"
                value={newCategory.description}
                onChange={(e) => setNewCategory({ ...newCategory, description: e.target.value })}
              />
            </div>
            <button
              type="submit"
              className="btn btn-primary"
            >
              添加分类
            </button>
          </form>
          
          <div className="bg-white dark:bg-dark-800 rounded-lg shadow overflow-hidden">
            <ul className="divide-y divide-gray-200 dark:divide-dark-700">
              {categories.map(category => (
                <li key={category.id} className="p-4 flex justify-between items-center">
                  <div>
                    <div className="font-medium text-dark-800 dark:text-dark-200">{category.name}</div>
                    {category.description && (
                      <div className="text-sm text-gray-500 dark:text-gray-400">{category.description}</div>
                    )}
                    <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                      {category.articleCount} 篇文章
                    </div>
                  </div>
                  <button
                    onClick={() => handleDeleteCategory(category.id)}
                    className="text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300"
                  >
                    <BsTrash />
                  </button>
                </li>
              ))}
              {categories.length === 0 && (
                <li className="p-4 text-center text-gray-500 dark:text-gray-400">
                  暂无分类
                </li>
              )}
            </ul>
          </div>
        </div>
        
        {/* 标签管理 */}
        <div>
          <h3 className="text-lg font-semibold mb-4 text-dark-700 dark:text-dark-300">标签管理</h3>
          
          <form onSubmit={handleAddTag} className="mb-6 bg-white dark:bg-dark-800 p-4 rounded-lg shadow">
            <div className="mb-4">
              <label className="label" htmlFor="tagName">标签名称</label>
              <input
                type="text"
                id="tagName"
                className="input"
                value={newTag.name}
                onChange={(e) => setNewTag({ ...newTag, name: e.target.value })}
                required
              />
            </div>
            <button
              type="submit"
              className="btn btn-primary"
            >
              添加标签
            </button>
          </form>
          
          <div className="bg-white dark:bg-dark-800 rounded-lg shadow p-4">
            <div className="flex flex-wrap gap-2">
              {tags.map(tag => (
                <div key={tag.id} className="flex items-center bg-gray-100 dark:bg-dark-700 px-3 py-1 rounded-full">
                  <span className="text-dark-700 dark:text-dark-300 mr-2">{tag.name}</span>
                  <span className="text-xs text-gray-500 dark:text-gray-400 mr-2">
                    ({tag.articleCount})
                  </span>
                  <button
                    onClick={() => handleDeleteTag(tag.id)}
                    className="text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300 text-sm"
                  >
                    <BsTrash />
                  </button>
                </div>
              ))}
              {tags.length === 0 && (
                <div className="w-full text-center text-gray-500 dark:text-gray-400 py-4">
                  暂无标签
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// 主仪表盘组件
const Dashboard = () => {
  return (
    <div className="max-w-7xl mx-auto">
      <h1 className="text-2xl font-bold mb-8 text-dark-800 dark:text-dark-200">管理后台</h1>
      
      <div className="grid grid-cols-1 lg:grid-cols-5 gap-8">
        {/* 侧边导航 */}
        <div className="lg:col-span-1">
          <nav className="bg-white dark:bg-dark-800 rounded-lg shadow overflow-hidden">
            <NavLink
              to="/admin/users"
              className={({ isActive }) => 
                `flex items-center px-4 py-3 text-dark-700 dark:text-dark-300 ${
                  isActive 
                    ? 'bg-primary-50 dark:bg-dark-700 border-l-4 border-primary-600' 
                    : 'hover:bg-gray-50 dark:hover:bg-dark-700'
                }`
              }
            >
              <BsPersonFill className="mr-3" />
              <span>用户管理</span>
            </NavLink>
            <NavLink
              to="/admin/content"
              className={({ isActive }) => 
                `flex items-center px-4 py-3 text-dark-700 dark:text-dark-300 ${
                  isActive 
                    ? 'bg-primary-50 dark:bg-dark-700 border-l-4 border-primary-600' 
                    : 'hover:bg-gray-50 dark:hover:bg-dark-700'
                }`
              }
            >
              <BsFileEarmarkTextFill className="mr-3" />
              <span>内容管理</span>
            </NavLink>
            <NavLink
              to="/admin/categories-tags"
              className={({ isActive }) => 
                `flex items-center px-4 py-3 text-dark-700 dark:text-dark-300 ${
                  isActive 
                    ? 'bg-primary-50 dark:bg-dark-700 border-l-4 border-primary-600' 
                    : 'hover:bg-gray-50 dark:hover:bg-dark-700'
                }`
              }
            >
              <BsTagFill className="mr-3" />
              <span>分类与标签</span>
            </NavLink>
          </nav>
        </div>
        
        {/* 内容区 */}
        <div className="lg:col-span-4">
          <div className="bg-white dark:bg-dark-800 rounded-lg shadow p-6">
            <Routes>
              <Route path="users" element={<UserManagement />} />
              <Route path="content" element={<ContentManagement />} />
              <Route path="categories-tags" element={<CategoryTagManagement />} />
              <Route path="/" element={
                <div className="text-center py-8">
                  <h2 className="text-xl font-bold mb-4 text-dark-800 dark:text-dark-200">
                    欢迎使用管理后台
                  </h2>
                  <p className="text-dark-600 dark:text-dark-300 mb-6">
                    请从左侧菜单选择要管理的内容
                  </p>
                </div>
              } />
            </Routes>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Dashboard; 